var express = require('express')
var user = express.Router()
var jwt = require('jsonwebtoken')
var uuid = require('uuid')
var mysql = require('mysql')
var sql = mysql.createConnection({
	host: '182.254.187.162',
	user: 'dbuser',
	password: 'Qwer781128..',
	database: 'CJHZ'
})
sql.connect()

/**
 * @api {post} /user/register 用户注册
 * @apiName 用户注册
 * @apiGroup User
 * @apiParam {String} userName 用户名
 * @apiParam {String} password  密码
 * @apiSuccess {number} id 用户id
 * @apiSuccess {String} userName 用户名
 * @apiSuccess {String} password  密码
 */

//用户注册
user.post('/register', (req, res, next) => {
	try {
		var info = req.body
		if (!info.userName || !info.password) {
			throw '参数错误！'
		}
		var SQL = 'INSERT INTO user_info  (user_name, password) VALUES (?,?) '
		var param = [info.userName, info.password]
		sql.query(SQL, param, (err, data) => {
			if (err) {
				throw err
			}
			res.send({
				static: 'ok',
				data: data,
				msg: '注册成功！'
			})
		})
	} catch (err) {
		res.send(err)
	}
})
//用户是否存在
user.get('/exist', (req, res, next) => {
	try {
		var info = req.query
		if (!info.userName) {
			throw '参数错误！'
		}
		var SQL = 'SELECT * FROM user_info WHERE user_name=' + info.userName
		sql.query(SQL, (err, data) => {
			if (err) {
				throw err
			}
			if (data.length > 1) {
				res.send({
					static: 'error',
					msg: '当前用户名已存在！'
				})
			} else {
				res.send({
					static: 'ok',
					msg: '当前用户名可用！'
				})
			}
		})
	} catch (err) {
		res.send(err)
	}
})
//用户登录
user.post('/login', (req, res, next) => {
	try {
		var info = req.body
		if (!info.userName || !info.password) {
			throw '参数错误！'
		}
		var SQL = 'SELECT * FROM user_info WHERE user_name = ' + info.userName
		sql.query(SQL, (err, data) => {
			if (err) {
				throw err
			}
			/*
      selector:本身是一个对象，用于储存用户信息的   
      'keven':加密字段，可以自己随便定义   
      expiresIn：过期时间单位是秒
      */

			if (data[0].password === info.password) {
				var token = jwt.sign(info, 'keven', {
					expiresIn: 180 //3分钟过期
				})
				res.send({
					static: 'ok',
					data: {
						userInfo: data,
						token: token
					},
					msg: '登录成功！'
				})
			} else {
				res.send({
					static: 'error',
					data: {},
					msg: '密码错误！'
				})
			}
		})
	} catch (err) {
		res.send(err)
	}
})
module.exports = user
